﻿using Application.Permissions.Models;
using Domain.Permissions.ValueObjects;
using System.Text.Json;

namespace Infrastructure.Files
{
    internal class PermissionLoader
    {
        /// <summary>
        /// 从指定文件目录中获取到权限列表
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <returns></returns>
        /// <exception cref="DirectoryNotFoundException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        public static IReadOnlyDictionary<string, IReadOnlyList<Permission>> LoadFromDirectory(string directoryPath)
        {
            //判断文件目录是否存在
            if (!Directory.Exists(directoryPath))
                throw new DirectoryNotFoundException($"权限目录不存在: {directoryPath}");

            var jsonFiles = Directory.GetFiles(directoryPath, "*.json", SearchOption.TopDirectoryOnly);

            Dictionary<string, IReadOnlyList<Permission>> result = [];
            //遍历读取到的json文件
            foreach (var file in jsonFiles)
            {
                if (!IsJsonFile(file))
                {
                    //Logger
                    continue;
                }
                var json = File.ReadAllText(file);

                var group = JsonSerializer.Deserialize<PermissionGroup>(json,new JsonSerializerOptions()
                {
                    PropertyNameCaseInsensitive = true
                })?? throw new InvalidOperationException($"无法解析权限文件: {file}");
                List<Permission> permissions = [];
                foreach (var dto in group.Permissions)
                {
                    permissions.Add(Permission.Create(dto.Name, dto.Sign, dto.Description));
                }
                result.Add(group.GroupName, permissions);
            }

            return result;
        }

        private static bool IsJsonFile(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                return false;

            string extension = Path.GetExtension(fileName);
            return string.Equals(extension, ".json", StringComparison.OrdinalIgnoreCase);
        }
    }
}
